package com.vhly.appspot.apns;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-4-12
 * Time: 17:33:57
 */

import com.google.appengine.api.datastore.ShortBlob;
import com.vhly.appspot.util.StreamUtil;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

public class ApnsServlet extends HttpServlet {
    private static Logger log = Logger.getLogger("KeyServlet");

//    private static Cache dbCache;
//
//    public void init(){
//        if(dbCache == null){
//            try{
//                CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
//                dbCache = cacheFactory.createCache(Collections.emptyMap());
//            }catch(CacheException ce){
//
//            }
//        }
//    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("load Resource");
        process(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.info("load Resource");
        process(request, response);
    }

    private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO implement process
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String method = request.getMethod();
        log.info("method:" + method);
        if (method.toLowerCase().equals("post")) {
            processPost(request, response);
        }
    }

    private void processPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int len = request.getContentLength();
        ServletInputStream in = request.getInputStream(); // 获取客户端的请求
        byte[] buf = null;
//        byte[] buf = StreamUtil.readStream(in);
        // 以下读取数据
        if (len > 0) {
            buf = new byte[len];
            int rlen = in.read(buf);
            if (rlen != len) {
                throw new IOException("read Error");
            }
        }else{
            buf = StreamUtil.readStream(in);
        }
        ByteArrayInputStream bin = null;
        DataInputStream din = null;
        byte[] deviceToken = new byte[32];
        if (buf != null && buf.length > 0) {
            log.info("buf :" + buf.length);
            try {
                bin = new ByteArrayInputStream(buf);
                din = new DataInputStream(bin);
                short action = din.readShort();             // 读取数据信息
                din.read(deviceToken, 0, 32);               // 读取DeviceToken
                int slen = din.readShort();
                log.info(" len:" + slen);
                byte[] bu = new byte[slen];
                din.readFully(bu);
                int product = din.readInt();
                String info = new String(bu, "UTF-8");
                log.info("read device info OK");
                String blob = StreamUtil.toHexString(deviceToken);
                PersistenceManager manager = PMF.get().getPersistenceManager();  // GAE 使用的存储数据库
                try {
                    // Device id = manager.getObjectById(Device.class, blob);
                    String query = "select from "+Device.class.getName()+" where deviceToken == '"+blob+"'";
                    List<Device> devs = (List<Device>) manager.newQuery(query).execute();
                    log.info("find obj");
                    if (devs == null || devs.size() == 0) {
                        log.info("not found create");
                        Device d = new Device();
                        d.setDeviceToken(blob);
                        d.setInformation(info);
                        d.setProduct(product);
                        manager.makePersistent(d);         // 保存数据库
                    } else {
                        log.info("find ok");
                        Device device = devs.get(0);
                        device.setInformation(info);
                        device.setProduct(product);
                        manager.makePersistent(device);      // 保存数据库
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log.info("save obj");
                    manager.close();
                }
                blob = null;
            } catch (Exception ex) {
                log.info("Error");
                ex.printStackTrace();
            } finally {
                StreamUtil.close(din);
                StreamUtil.close(bin);
            }
        } else {
            log.info("buf len 0");
        }
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
